package com.nettyAdvanced.p2_short;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author： pang-yun
 * @date： 2021-09-14 16:54
 * 功能目的 ：用于 短连接 解决 黏包现象   但是不能解决半包现象
 */

public class ShortClient {

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            send();
        }
        System.out.println("finish......");
    }

    private static void send() {
        NioEventLoopGroup work = new NioEventLoopGroup();
        try {
            ChannelFuture channelFuture = new Bootstrap()
                    .group(work)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    ByteBuf buffer = ctx.alloc().buffer(16);
                                    buffer.writeBytes(new byte[]{0, 1, 2, 3, 4, 5, 7, 8,9,10,11,12,13,14,15,16,17});
                                    ctx.writeAndFlush(buffer);
                                    ctx.channel().close();
                                }
                            });
                        }
                    }).connect(new InetSocketAddress(9999));

            Channel channel = channelFuture.sync().channel();
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            work.shutdownGracefully();
        }
    }
}
